<template>
  <div class="header-tabs">
    <div class="tabs-container" @mouseleave="handleContainerLeave">
      <div class="tabs-wrapper">
        <div
            v-for="tab in tabs"
            :key="tab.id"
            class="tab-item"
            @click="handleTabClick(tab.id)"
            @mouseenter="handleTabEnter(tab.id)"
        >

          <div class="tab-title" :class="{ active: activeTab === tab.id }" >
            <a :href="`/classify/${tab.url}-${tab.id}.html`" :title="tab.title" style="color:#000000">{{ tab.title }}</a>
          </div>
        </div>
      </div>
    </div>

    <!-- 桌面端面板 -->
    <div v-if="activeTab && !isMobile && getActiveTabComponent?.children?.length" class="tab-panel desktop-panel" @mouseenter="isPanelHovered = true"
         @mouseleave="handlePanelLeave">
      <keep-alive>
        <component
          :is="getActiveTabComponent?.component"
          :children="getActiveTabComponent?.children"
        />
      </keep-alive>
    </div>

    <!-- 移动端面板 -->
    <div v-if="activeTab && isMobile && getActiveTabComponent?.children?.length" class="tab-panel mobile-panel">
      <div class="mobile-panel-header">
        <span>{{ getActiveTabTitle }}</span>
        <span class="close-icon" @click="activeTab = null">×</span>
      </div>
      <div class="mobile-panel-content">
        <keep-alive>
          <component
            :is="getActiveTabComponent?.component"
            :children="getActiveTabComponent?.children"
          />
        </keep-alive>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {ref, computed, onMounted, onUnmounted} from 'vue';
import { useRouter } from 'vue-router';
import { defineAsyncComponent, markRaw } from 'vue';
const WomenPanel = markRaw(defineAsyncComponent(() => import('./WomenPanel.vue')));
import { getclassify } from '@/api/home';
import {Session} from "@/utils/storage";

// 添加公告栏显示状态
const isAnnouncementVisible = ref(true);

// 计算 tab-panel 的 top 值
const panelTopPosition = computed(() => {
  return isAnnouncementVisible.value ? '92px' : '42px';
});

interface TabItem {
  id: string;
  title: string;
  component: any;
  name: string;
  children: any[];
  icon?: string;
  manual_order?: number;
  pid?: string;
  url?: string;
  weigh?: number;
}

interface ClassifyItem {
  id: string;
  name: string;
  children: any[];
  icon?: string;
  manual_order?: number;
  pid?: string;
  url?: string;
  weigh?: number;
}

const tabs = ref<TabItem[]>([]);
const activeTab = ref<string | null>(null);
const isPanelHovered = ref(false);
const isMobile = ref(false);
const classifyList = ref<ClassifyItem[]>([]);
const router = useRouter();

// 验证tab数据是否完整有效
const isValidTabData = (data: any[]): boolean => {
  if (!Array.isArray(data) || data.length === 0) {
    return false;
  }

  // 检查数据结构是否完整
  for (const item of data) {
    if (!item.id || !item.title || !item.children) {
      return false;
    }
  }

  return true;
}

// 获取分类列表
const getclassifyList = async () => {
  // 首先检查session storage
  const tabList = Session.get('tab')

  if(tabList && tabList.length > 0){
    // 处理从缓存获取的tabs数据，确保component是正确的组件实例
    tabs.value = tabList.map((item: TabItem) => ({
      ...item,
      component: WomenPanel, // 始终使用正确的组件引用，而不是序列化后的对象
    }));
    return;
  }

  try {
    // 尝试从__INITIAL_INDEX__获取数据
    if((window as any).__INITIAL_INDEX__ && (window as any).__INITIAL_INDEX__.classify){
      const res = (window as any).__INITIAL_INDEX__.classify;
      classifyList.value = res;
      tabs.value = classifyList.value.map(item => ({
        id: item.id,
        title: item.name,
        component: WomenPanel,
        name: item.name,
        children: item.children,
        icon: item.icon,
        manual_order: item.manual_order,
        pid: item.pid,
        url: item.url,
        weigh: item.weigh,
      }));

      // 同时保存到localStorage防止session丢失
      Session.set('tab', tabs.value);
      try {
        localStorage.setItem('frsst_tabs', JSON.stringify(tabs.value));
      } catch (e) {
        console.error('无法保存到localStorage', e);
      }

      return; // 成功获取数据后返回
    }

    // 尝试从localStorage获取（作为备用）
    try {
      const localTabs = localStorage.getItem('frsst_tabs');
      if (localTabs) {
        const parsedTabs = JSON.parse(localTabs);
        if (isValidTabData(parsedTabs)) {
          // 处理从localStorage获取的tabs数据，确保component是正确的组件实例
          tabs.value = parsedTabs.map((item: TabItem) => ({
            ...item,
            component: WomenPanel, // 始终使用正确的组件引用
          }));
          // 同步回session
          Session.set('tab', tabs.value);
          return;
        } else {
          console.warn('localStorage中的数据结构不完整，不使用');
        }
      }
    } catch (e) {
      console.error('无法从localStorage获取数据', e);
    }

    // 如果前面都没有数据，则尝试API调用
    const res = await getclassify();

    if (res && res.result) {
      classifyList.value = res.result;
      tabs.value = classifyList.value.map(item => ({
        id: item.id,
        title: item.name,
        component: WomenPanel,
        name: item.name,
        children: item.children,
        icon: item.icon,
        manual_order: item.manual_order,
        pid: item.pid,
        url: item.url,
        weigh: item.weigh,
      }));

      // 保存到session和localStorage
      Session.set('tab', tabs.value);
      try {
        localStorage.setItem('frsst_tabs', JSON.stringify(tabs.value));
      } catch (e) {
        console.error('无法保存到localStorage', e);
      }
    }
  } catch (error) {
    console.error('获取分类列表失败:', error);
    // 设置默认值以防错误
    tabs.value = [];
    classifyList.value = [];
  }
}
// 获取当前激活的面板组件
const getActiveTabComponent = computed(() => {
  const tab = tabs.value.find(t => t.id === activeTab.value);

  if (!tab) {
    return null;
  }

  // 确保WomenPanel组件可用
  if (!tab.component) {
    return {
      component: WomenPanel,
      children: tab.children || []
    };
  }

  return {
    component: tab.component,
    children: tab.children || []
  };
});

// 获取当前激活的标签标题
const getActiveTabTitle = computed(() => {
  const tab = tabs.value.find(t => t.id === activeTab.value);
  return tab ? tab.title : '';
});

// 容器离开事件处理
const handleContainerLeave = () => {
  if (!isMobile.value) {
    setTimeout(() => {
      if (!isPanelHovered.value) {
        activeTab.value = null;
      }
    }, 100); // 延迟关闭，给鼠标进入面板留时间
  }
};

// 鼠标进入标签时的处理
const handleTabEnter = (tabId: string) => {
  if (!isMobile.value) {
    activeTab.value = tabId;

    // 检查对应tab是否存在
    const tab = tabs.value.find(t => t.id === tabId);
    if (!tab) {
      console.warn('找不到对应的tab数据:', tabId);
    } else if (!tab.children || tab.children.length === 0) {
      console.warn('该tab没有children数据:', tabId);
    } else {
      // console.log('成功激活tab:', tabId, '子项数量:', tab.children?.length || 0);
    }

    // 确保面板可见
    isPanelHovered.value = true;
  }
};

// 鼠标离开面板时的处理
const handlePanelLeave = () => {
  isPanelHovered.value = false;
  setTimeout(() => {
    // 检查鼠标是否已经回到tab区域，否则关闭
    if (!isPanelHovered.value) {
      activeTab.value = null;
    }
  }, 100);
};

// 点击标签时的处理（移动端）
const handleTabClick = (tabId: string) => {
  if (isMobile.value) {
    activeTab.value = activeTab.value === tabId ? null : tabId;
  }
};

// 检查窗口大小并设置移动端标志
const checkWindowSize = () => {
  isMobile.value = window.innerWidth < 1040;
};
// 处理公告栏关闭事件
const handleAnnouncementClose = () => {
  isAnnouncementVisible.value = false;
};

onMounted(() => {
  checkWindowSize();
  window.addEventListener('resize', checkWindowSize);

  // 添加事件监听
  window.addEventListener('announcement-closed', handleAnnouncementClose);

  // 确保分类数据已加载
  if (!tabs.value || tabs.value.length === 0) {
    console.log('组件挂载时发现tabs为空，重新加载数据');
    getclassifyList();
  } else {
    console.log('组件挂载时tabs已有数据，数量:', tabs.value.length);
  }
});

onUnmounted(() => {
  window.removeEventListener('resize', checkWindowSize);
  // 移除公告栏事件监听
  window.removeEventListener('announcement-closed', handleAnnouncementClose);
});
</script>

<style lang="scss" scoped>
.header-tabs {
  width: 100%;
  position: relative;
}

.tabs-container {
  max-width: 1200px;
  margin: 0 auto;
  position: relative;
  background-color: #fff;
  z-index: 101;
}

.tabs-wrapper {
  display: flex;
  justify-content: space-around;
}

.tab-item {
  //padding: 0 20px;
  cursor: pointer;
  text-align: center;

  .tab-title {
    font-weight: 500;
    transition: color 0.3s;

    &.active {
      color: #ff0000;
    }
  }

  &:hover .tab-title {
    color: #ff0000;
  }
  &:hover a {
    color: #ff0000;
  }
}

.tab-panel {
  position: fixed;
  left: 0;
  right: 0;
  width: 100%;
  background-color: #fff;
  color: #000;
  z-index: 100;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  top: v-bind(panelTopPosition);
  transition: top 0.3s ease;
}


.desktop-panel {
  padding: 0;
}

.desktop-panel :deep(.panel-content) {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

.mobile-panel {
  position: fixed;
  top: 155px;
  height: calc(100vh - 155px);
  overflow-y: auto;
  padding: 0;

  .mobile-panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background-color: #f5f5f5;
    font-weight: bold;

    .close-icon {
      font-size: 24px;
      cursor: pointer;
    }
  }
}

.mobile-panel-content {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

@media (max-width: 1040px) {
  .tabs-container {
    justify-content: flex-start;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
  }

  .tabs-wrapper {
    justify-content: flex-start;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */
    &::-webkit-scrollbar {
      display: none; /* Chrome, Safari, Opera */
    }
  }

  .tab-item {
    padding: 10px 15px;
    white-space: nowrap;
  }
}
</style>
